import {Component, ElementRef, Input} from '@angular/core';
@Component({
    selector: 'highlight-keyword',
    template: `
        <div [innerHTML]="_content" class="file-box"></div>
    `
})
export class HighlightKeyword {
    _content: string;
    _keywords: Array<string>;

    @Input() content: string;

    @Input() 
    set keywords(value: string) {
        this._keywords = value.split(',');
    }
    
    get keywords(): string {
        return this._keywords.join(',');
    } 

    constructor(
    ) {}

    ngOnInit() {
        this._content = this._replace(this.content, this._keywords);
    }

    _replace(text: string, keywords: Array<string>): string {
        // 转义尖括号
        // text = text.replace(/\</ig, "&lt;").replace(/\>/ig, "&gt;");

        for (var keyword of keywords) {
            var r = new RegExp('('+keyword.replace(/[(){}.+*?^&|\\\[\]]/g, '\\$&') + ')', 'ig');
            text = text.replace(r, '<span class="keyword">$1</span>');
        }
        return text;
    }
}